package com.bocai.controller;

import com.bocai.bean.CompetitionInfo;
import com.bocai.bean.CountryInfo;
import com.bocai.bean.CustomEvent;
import com.bocai.bean.TCMObject;
import com.bocai.service.ICompetitionService;
import com.bocai.service.ICountryService;
import com.bocai.service.ICustomEventService;
import com.bocai.utils.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Cemetery on 2018-04-10.
 */
@Controller
@RequestMapping("country")
public class CountryController {

    @Autowired
    private ICountryService countryService;

    @Autowired
    private ICompetitionService competitionService;

    @Autowired
    private ICustomEventService customEventService;

    @ApiOperation(value = "更新数据库国家列表", notes = "")

    @RequestMapping(value = "/updateCountry", method = RequestMethod.GET)
    @ResponseBody
    public ResponseData updateCountry() {
        ResponseData data = new ResponseData();
        data.setCodeEnum(CodeEnum.SUCCESS);

        Map<String, Object> business_zh = new HashMap<>();

        business_zh.put("sportId", SysConstant.SPORT_TYPE_FOOTBALL);
        business_zh.put("language", '6');

        TCMObject tcmObject_zh = GetResultUtils.getObject(SysConstant.COUNTRY_LIST, business_zh);
        JSONArray countrys_zh = tcmObject_zh.getBody().getJSONArray("data");

        List<CountryInfo> countryList = new ArrayList<>();
        for (int i = 0; i < countrys_zh.size(); i++) {
            JSONObject jsonObject = countrys_zh.getJSONObject(i);
            Integer countryId = jsonObject.getInt("countryId");
            String countryName = jsonObject.getString("countryName");

            CountryInfo countryInfo = new CountryInfo();
            countryInfo.setCountryId(countryId);
            countryInfo.setCountryNameZh(countryName);

            countryList.add(countryInfo);
        }

        this.countryService.insertCountrys(countryList);

        countryList.clear();

        Map<String, Object> business_en = new HashMap<>();

        business_en.put("sportId", SysConstant.SPORT_TYPE_FOOTBALL);
        business_en.put("language", '1');

        TCMObject tcmObject_en = GetResultUtils.getObject(SysConstant.COUNTRY_LIST, business_en);
        JSONArray countrys_en = tcmObject_en.getBody().getJSONArray("data");

        for (int i = 0; i < countrys_en.size(); i++) {
            JSONObject jsonObject = countrys_en.getJSONObject(i);
            Integer countryId = jsonObject.getInt("countryId");
            String countryName = jsonObject.getString("countryName");

            CountryInfo countryInfo = new CountryInfo();
            countryInfo.setCountryId(countryId);
            countryInfo.setCountryNameEn(countryName);

            countryList.add(countryInfo);
        }

        this.countryService.updateCountrys(countryList);

        return data;
    }

    @ApiOperation(value = "更新所有赛事到数据库", notes = "")

    @RequestMapping(value = "/updateCompetition", method = RequestMethod.GET)

    @ResponseBody
    public ResponseData updateCompetition() {
        ResponseData data = new ResponseData();
        data.setCodeEnum(CodeEnum.SUCCESS);

        List<CountryInfo> countrys = (List<CountryInfo>) this.countryService.selectAllCountry(new ResponseData()).getResults();

        List<CompetitionInfo> list = new ArrayList<>();

        for (CountryInfo countryInfo : countrys){
            Integer countryId = countryInfo.getCountryId();

            Map<String, Object> competitionMap = new HashMap<>();

            competitionMap.put("sportId", SysConstant.SPORT_TYPE_FOOTBALL);
            competitionMap.put("language", "1");
            competitionMap.put("countryId", countryId);

            TCMObject tcmObject = GetResultUtils.getObject(SysConstant.COMPETITION_LIST, competitionMap);
            JSONArray competitions = tcmObject.getBody().getJSONArray("data");

            for (int i = 0; i < competitions.size(); i++) {
                JSONObject jsonObject = competitions.getJSONObject(i);
                try {

                    Integer id = jsonObject.getInt("competitionId");
                    String en = jsonObject.getString("competitionName");

                    Map<String,Object> map = new HashMap<>();
                    map.put("competitionId",id);
                    map.put("language","6");

                    String zn = GetResultUtils.getObject(SysConstant.COMPETITION_INFO,map).getBody().getJSONObject("data").getString("competitionName");

                    CompetitionInfo competitionInfo = new CompetitionInfo();
                    competitionInfo.setCompetitionId(id);
                    competitionInfo.setCompetitionNameEn(en);
                    competitionInfo.setCountryId(countryId);
                    competitionInfo.setCompetitionNameZh(zn);

                    list.add(competitionInfo);
                }catch (Exception e){
                    System.out.println(jsonObject);
                    e.printStackTrace();
                }

            }
//            break;
        }

        this.competitionService.insertCompetitions(list);

        return data;
    }


    @ApiOperation(value = "查询国家列表", notes = "获取国家列表")

    @RequestMapping(value = "/getCountryList", method = RequestMethod.GET)
    @ResponseBody
    public ResponseData searchCountry() {
        ResponseData data = new ResponseData();
        data.setCodeEnum(CodeEnum.SUCCESS);

        return this.countryService.selectAllCountry(data);
    }

    @ApiOperation(value = "服务端查询所有赛事列表", notes = "查询赛事列表")

    @RequestMapping(value = "/competitionAllList", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "tabId", dataType = "Integer", required = false, value = "标签id", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "keyword", dataType = "string", required = false, value = "筛选关键词", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "status", dataType = "int", required = false, value = "0已启用，1禁止", defaultValue = ""),
    })
    @ResponseBody
    public ResponseData competitionAllList(Integer status,Integer tabId,String keyword) {
        ResponseData data = new ResponseData();
        data.setCodeEnum(CodeEnum.SUCCESS);
        return this.competitionService.selectAllCompetition(null,status,tabId,keyword,data);
    }

    @ApiOperation(value = "服务端查询比赛列表", notes = "查询比赛列表")

    @RequestMapping(value = "/eventList", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "countryId", dataType = "Integer", required = false, value = "国家id", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "enabled", dataType = "int", required = false, value = "是否包含被禁用的比赛，不传为包含", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "competitionId", dataType = "Integer", required = false, value = "赛事id", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "date", dataType = "string", required = true, value = "比赛开始日期 yyyy-MM-dd", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "endDate", dataType = "string", required = false, value = "比赛开始日期 yyyy-MM-dd 和date是时间段，如果不传只查询date当天", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "keyword", dataType = "string", required = false, value = "筛选关键词,球队名，比赛id", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "state", dataType = "int", required = false, value = "状态参考EventState,0未开赛，3进行中,-1被禁止", defaultValue = ""),
    })
    
    @ResponseBody
    public ResponseData eventList(Integer countryId,
                                  Integer competitionId,
                                  String date,
                                  String endDate,
                                  String keyword,
                                  Integer enabled,
                                  Integer state) {
        ResponseData responseData = new ResponseData();
        responseData.setCodeEnum(CodeEnum.SUCCESS);

        CodeEnum codeEnum = ObjUtils.validateParams(new Object[]{date});

        if (ObjUtils.isNotEmpty(codeEnum)) {
            responseData.setCodeEnum(CodeEnum.CODE_90001);
            return responseData;
        }

        Map<String, Object> map = new HashMap<>();
        if (null != countryId) {
            map.put("countryId", countryId);
        }
        if (null != competitionId) {
            map.put("competitionId", competitionId);
        }

        Long beginTime = null;
        Long endTime = null;

        try {

            beginTime = DateUtils.parse(date + " 00:00:00").getTime();

            if (null != endDate) {
                endTime = DateUtils.parse(endDate + " 23:59:59").getTime();
            } else {
                endTime = DateUtils.parse(date + " 23:59:59").getTime();
            }

        } catch (ParseException e) {
            e.printStackTrace();
            responseData.setCodeEnum(CodeEnum.CODE_90002);
            return responseData;
        }

        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        map.put("sportId", SysConstant.SPORT_TYPE_FOOTBALL);
        map.put("language", SysConstant.LANGUAGE_TYPE);

        TCMObject object = GetResultUtils.getObject(SysConstant.EVENT_LIST, map);

        JSONArray jsonArray = null;

        try {
         jsonArray = object.getBody().getJSONArray("data");
        }catch (Exception e){
            responseData.setCodeEnum(CodeEnum.CODE_70001);
            return responseData;
        }

        List<JSONObject> temp = new ArrayList<>();

        //被禁用列表,
        CustomEvent cus = new CustomEvent();
        List<CustomEvent> enabledEvents = this.customEventService.selectEvents(cus);

        for (int i = 0; i < jsonArray.size(); i++) {

            JSONObject event = jsonArray.getJSONObject(i);
            event.put("enabled", 0);
            Integer eventId = event.getInt("eventId");

            Boolean isEnabled = false;

            for (CustomEvent enabledEvent : enabledEvents) {
                if (enabledEvent.getEventId().equals(eventId)) {

                    event.put("isHot", enabledEvent.getIsHot());
                    event.put("enabled", enabledEvent.getIsEnable());
                    isEnabled = enabledEvent.getIsEnable() == 1;

                    break;
                }
            }

            if (isEnabled && null != enabled) {
                continue;
            }

            //如果有关键词，处理关键词
            if (null != keyword && keyword.trim().length() > 0) {

                String competitionName = event.getString("competitionName");
                String homeTeam = event.getString("homeTeamName");
                String awayTeam = event.getString("awayTeamName");
                if (!(competitionName.contains(keyword) ||
                        homeTeam.contains(keyword) ||
                        awayTeam.contains(keyword) ||
                        (eventId + "").contains(keyword))) {
                    continue;
                }
            }

            //判断是否需要筛选状态
            if (null != state) {
                if (state == -1){
                    if (event.getInt("enabled") != 1){
                        continue;
                    }
                }else {
                    Integer event_state = event.getInt("state");
                    if (event_state != state) {
                        continue;
                    }
                }
            }

            temp.add(event);
        }


        responseData.setResults(temp);

        return responseData;
    }


    @ApiOperation(value = "查询比赛详情", notes = "查询比赛详情")

    @RequestMapping(value = "/eventInfo", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "eventId", dataType = "Integer", required = false, value = "比赛", defaultValue = "1504400"),
    })
    @ResponseBody
    public ResponseData eventInfo(Integer eventId) {

        ResponseData responseData = new ResponseData();
        responseData.setCodeEnum(CodeEnum.SUCCESS);

        CodeEnum codeEnum = ObjUtils.validateParams(new Object[]{eventId});

        if (ObjUtils.isNotEmpty(codeEnum)) {
            responseData.setCodeEnum(CodeEnum.CODE_90001);
            return responseData;
        }

        Map<String, Object> map = new HashMap<>();

        map.put("eventId", eventId);
        map.put("sportId", SysConstant.SPORT_TYPE_FOOTBALL);
        map.put("language", SysConstant.LANGUAGE_TYPE);

        TCMObject object = GetResultUtils.getObject(SysConstant.EVENT_INFO, map);

        responseData.setResults(object.getBody().getJSONObject("data"));

        return responseData;
    }
}
